<template>
    <div class="todo-box">
        <el-input v-model="todo" @keypress.native.enter="onEnter" placeholder="enter todo"/>
        <todo-item v-for="item in sortTodos"
                   :key="item.id"
                   :item="item"
                   @delete="onDelete"
                   @done="onDone"/>
    </div>
</template>

<script lang="ts">
import { ElInput } from 'element-plus';
import TodoItem from '@/components/TodoItem.vue';
import { Todo } from '@/utils/types';
import { computed, defineComponent, Ref, ref, watch } from 'vue';
import { $todoStore } from '../stores/todo';

export default defineComponent({
    name: 'TodoBox',
    components: {
        TodoItem,
        ElInput,
    },
    setup() {
        const todo = ref('');

        const sortTodos = computed(() => $todoStore.sortTodos);

        function onEnter() {
            $todoStore.addTodo(new Todo(todo.value));
            todo.value = '';
        }

        function onDelete(id: string) {
            $todoStore.deleteTodo(id);
        }

        function onDone(id: string) {
            $todoStore.doneTodo(id);
        }

        watch(
            () => $todoStore.todos,
            () => {
                localStorage.setItem('todos', JSON.stringify($todoStore.todos));
            },
            {
                deep: true,
            },
        );
        return {
            todo,
            sortTodos,
            onDone,
            onEnter,
            onDelete,
        };
    },
});
</script>

<style lang="scss" scoped>
.todo-box {
    width: 500px;
}

.el-input {
    margin-bottom: 10px;
}
</style>
